package cn.wolfcode.rbac.springSecurity.detail;

import cn.wolfcode.rbac.domain.Employee;
import cn.wolfcode.rbac.mapper.EmployeeMapper;
import cn.wolfcode.rbac.mapper.PermissionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 自定义数据源：MyUserDetailsService
 */
@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.根据用户从数据库中查询用户的信息
        Employee employee = employeeMapper.selectByName(username);
        if(employee == null){
            throw new UsernameNotFoundException("用户名或密码错误");
        }

        //2.根据用户的信息从数据库中查询所具有的权限
        List<String> expressions = null;
        if(employee.getAdmin()){
            //1.如果是超级管理员,则分配所有的权限
            expressions = permissionMapper.selectExpression();
        }else{
            //2.如果不是超级管理员，则根据id查询这个用户所拥有的权限
            Long employeeId = employee.getId();
            expressions = permissionMapper.queryExpressionByEmployeeId(employeeId);
        }
        MyUserDetails myUserDetails = new MyUserDetails(employee,expressions);
        return myUserDetails;
    }
}
